package com.rhok.wthru_client;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.rhok.wthru_client.servermsgs.ServerMessageOpaque;
import com.rhok.wthru_client.servermsgs.ServerMessageRegister;
import com.rhok.wthru_client.servermsgs.ServerMessageTask;

public class GCMIntentService extends GCMBaseIntentService {

	
	private static final String LOG_TOPIC = "WTHRU_GCMIntentService";

	public GCMIntentService() {
		super(GlobalConfiguration.SENDER_ID);
	}
	
	@Override
	protected void onError(Context context, String errorId) {
		Log.i(LOG_TOPIC, "Received error: " + errorId);
		// TODO: display the error message
	}

	@Override
	protected void onMessage(Context context, Intent intent) {
		// TODO Auto-generated method stub
		Log.i(LOG_TOPIC, "Message received: " + intent.describeContents());
	}

	@Override
	protected void onRegistered(Context context, String registrationId) {
		Log.i(LOG_TOPIC, "Device registered: regId = " + registrationId);
		
		ServerMessageRegister smr = new ServerMessageRegister(context);
		smr.setGCMId(registrationId);
		ServerMessageOpaque opq = new ServerMessageOpaque(smr, new OnTaskCompleted<String>() {

			@Override
			public void onTaskCompleted(String returnValue) {
				// TODO Auto-generated method stub
				GlobalConfiguration globalConf = GlobalConfiguration.getInstance(getApplicationContext());
				globalConf.setUuid(returnValue);
				Intent i = new Intent(getApplicationContext(), MainActivity.class);
				startActivity(i);
			}			
		});
		new ServerMessageTask().execute(opq);
	}

	@Override
	protected void onUnregistered(Context context, String registrationId) {
		Log.i(LOG_TOPIC, "Device unregistered: regId = " + registrationId);
		// TODO: message the server of unregistration, and remove globalConf
	}

}
